<?php
namespace Common\Service;

class SettingService
{
    /**
     * 获取系统变量
     * @param  array
     * @return [type]
     */
    public function get($keys)
    {
        $setting = $this->getAll();

        if (is_string($keys)) {

            return $setting[$keys]['value'];

        } elseif (is_array($keys)) {

            $result = [];
            foreach ($keys as $key) {

                if (array_key_exists($key, $setting)) {

                    $result[$key] = $setting[$key]['value'];
                } else {

                    $result[$key] = null;
                }
            }

            return $result;
        }
    }

    /**
     * 设置键值
     * @param [type]
     * @param string
     */
    public function set($key, $value, $refresh)
    {
        $where = [
            'key' => $key,
        ];

        $is_exists = M('setting')->where($where)->find();

        if ($is_exists) {

            $result = M('setting')
                ->where($where)
                ->setField('value', $value);
        } else {

            $key_val = [
                'key'   => $key,
                'value' => $value,
            ];
            $result = M('setting')->add($key_val);
        }

        if ($refresh) {
            S('setting', null);
        }

    }

    /**
     * 从表里获取所有
     * @return [type]
     */
    private function getAllFromTable()
    {
        $setting = M('setting')
            ->field('key,value,description')
            ->limit(false)
            ->lists('key');
        return $setting;
    }

    /**
     * 清空setting缓存
     * @return [type] [description]
     */
    public function clean()
    {
        return S('setting', null);
    }

    /**
     * 从缓存中取
     * @return [type]
     */
    private function getAll()
    {
        $setting = S('setting');
        if (!$setting) {
            $setting = $this->getAllFromTable();
            S('setting', $setting);
        }

        return $setting;
    }
}
